你可以使用@RestClientTest
测试REST客户端,它默认会自动配置Jackson和GSON,配置RestTemplateBuilder
,并添加MockRestServiceServer
支持。你需要将@RestClientTest
的value
或components
属性值设置为待测试类:
@RunWith(SpringRunner.class)
@RestClientTest(RemoteVehicleDetailsService.class)
public class ExampleRestClientTest {
@Autowired
private RemoteVehicleDetailsService service;
@Autowired
private MockRestServiceServer server;
@Test
public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails()
throws Exception {
this.server.expect(requestTo("/greet/details"))
.andRespond(withSuccess("hello", MediaType.TEXT_PLAIN));
String greeting = this.service.callRestService();
assertThat(greeting).isEqualTo("hello");
}
}
在附录中可以查看@RestClientTest
启用的自动配置列表。